package com.miaosmart.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;

/**
 * 阿里云OSS工具类
 */
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String ossDomain;
    private String customDomain;

    /**
     * 文件上传
     *
     * @param bytes 文件字节数组
     * @param objectName 文件在OSS中的存储名称
     * @return 文件访问URL
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //构建文件访问路径
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        String originalUrl = stringBuilder.toString();
        log.info("文件上传到OSS:{}", originalUrl);

        // 如果配置了自定义域名，则替换为自定义域名
        String finalUrl = replaceWithCustomDomain(originalUrl);
        log.info("返回的文件URL:{}", finalUrl);

        return finalUrl;
    }

    /**
     * 替换OSS域名为自定义域名
     * @param originalUrl 原始OSS URL
     * @return 替换后的URL
     */
    private String replaceWithCustomDomain(String originalUrl) {
        // 如果没有配置自定义域名，直接返回原URL
        if (customDomain == null || customDomain.isEmpty()) {
            return originalUrl;
        }
        
        // 如果没有配置OSS域名，使用默认构建的域名进行替换
        if (ossDomain == null || ossDomain.isEmpty()) {
            // 构建默认的OSS域名
            String defaultOssDomain = "https://" + bucketName + "." + endpoint + "/";
            if (originalUrl.startsWith(defaultOssDomain)) {
                return originalUrl.replace(defaultOssDomain, customDomain);
            }
        } else {
            // 使用配置的OSS域名进行替换
            if (originalUrl.startsWith(ossDomain)) {
                return originalUrl.replace(ossDomain, customDomain);
            }
        }
        
        // 如果都不匹配，返回原URL
        return originalUrl;
    }

}